<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button icon="el-icon-plus" size="small" type="primary" @click="showDialog = true">新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="roles">
              <el-table-column type="index" label="序号" width="120" />
              <el-table-column prop="name" label="角色名称" width="240" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template v-slot="{row}">
                  <el-button size="small" type="success" @click="hAssign(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination :current-page="page.page" :page-sizes="[2, 3, 5, 10]" :page-size="page.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!-- 新增弹框 -->
    <el-dialog :title="roleForm.id ? '编辑弹层' : '新增弹层'" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="showDialog" @closed="hCancel">
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" @click="hCancel">取消</el-button>
          <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 分配权限弹层 -->
    <el-dialog title="分配权限" :visible.sync="showDialogAssign" :close-on-click-modal="false" :close-on-press-escape="false">
      <AssignPermission v-if="showDialogAssign" :id="curId" @close="showDialogAssign = false" />
    </el-dialog>
  </div>
</template>

<script>
import { getRoles, delRoles, addRoles, editRoles } from '@/api/roles'
import AssignPermission from './assignPermission'

export default {
  components: { AssignPermission },
  data() {
    return {
      page: {
        page: 1,
        pagesize: 2
      },
      roles: [],
      total: 0,
      showDialog: false,
      showDialogAssign: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      curId: ''
    }
  },
  created() {
    this.getRoles()
  },
  methods: {
    async getRoles() {
      try {
        const res = await getRoles(this.page)
        this.roles = res.data.rows
        this.total = res.data.total
      } catch (e) {
        console.log(e)
      }
    },
    handleSizeChange(pagesize) {
      this.page.pagesize = pagesize
      this.getRoles()
    },
    handleCurrentChange(page) {
      this.page.page = page
      this.getRoles()
    },
    // 删除角色
    async hDel(id) {
      const result = await this.$confirm('真的要删除此角色吗？', '提示', { type: 'warning' }).catch(e => e)
      if (result !== 'confirm') return
      try {
        const res = await delRoles(id)
        if (this.roles.length === 1 && this.page.page > 1) {
          this.page.page--
        }
        this.$message.success(res.message)
        this.getRoles()
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 添加角色
    async hSubmit() {
      // // 1、兜底校验
      const valid = await this.$refs.roleForm.validate().catch(e => e)
      if (!valid) return
      let res = null
      // 根据 id 判断用户是编辑还是添加，编辑时 roleForm 里面回填了 id,而添加时没有 id
      if (this.roleForm.id) {
        res = await editRoles(this.roleForm).catch(e => e)
      } else {
        res = await addRoles(this.roleForm).catch(e => e)
        // 当最后一页满了之后需要新开一页
        /*
        当总条数能够整除每页显示条数的时候说明最后一页是满的，此时根据下面的条件，无法跳转道最后新开的一页
        只能够手动判断，把本地的 total 加 1，再向上取整
      */
        if (this.total % this.page.pagesize === 0) {
          this.total++
        }
        // 添加完成之后跳转到最新的数据（跳转到最后一页）
        this.page.page = Math.ceil(this.total / this.page.pagesize)
      }
      // 2、验证通过发送请求
      // 3、根据结果通知用户
      if (res.code !== 10000) return this.$message.error(res.message)
      this.$message.success(res.message)
      // 4、关闭 dialog
      this.showDialog = false
      // 5、重新渲染视图
      this.getRoles()
    },
    // 取消按钮
    hCancel() {
      // 清空表单报错验证
      this.$refs.roleForm.resetFields()
      // 清空表单
      this.roleForm = {
        name: '',
        description: ''
      }
      // 关闭dialog
      this.showDialog = false
    },
    // 编辑角色详情
    hEdit(row) {
      // 数据回填
      this.roleForm = { ...row }
      // 打开 dialog
      this.showDialog = true
    },
    hAssign(id) {
      this.showDialogAssign = true
      this.curId = id
    }
  }
}
</script>

